package com.example.yt_app.Activity.Device;




import android.animation.Animator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import com.example.yt_app.Activity.BaseActivity.SwipeBackBaseActivity;
import com.example.yt_app.AppManager;
import com.example.yt_app.R;
import com.example.yt_app.Urils.AnimUtil;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.example.yt_app.bean.Onenet.Data;
import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by dell on 2021/7/26.
 */
@SuppressWarnings("ALL")
public class LedActivity extends SwipeBackBaseActivity {
    private OkHttpClient okHttpClient;
    @BindView(R.id.detail_toolbar)
    Toolbar toolbar;
    @BindView(R.id.sai_id)
    TextView Sai_id;
    @BindView(R.id.online)
    TextView Online;
    @BindView(R.id.updatetime)
    TextView Updatetime;
    @BindView(R.id.create_time)
    TextView Create_time;
    @BindView(R.id.zhuangtai)
    TextView Zhuangtai;

    @BindView(R.id.switch_led)
    FloatingActionButton img;

    @BindView(R.id.iv_add)
    ImageView iv_add;


    private TextView tv_1, tv_2, tv_3, tv_4, tv_5;
    private PopupWindow mPopupWindow;

    private AnimUtil animUtil;
    private float bgAlpha = 1f;
    private boolean bright = false;

    private static final long DURATION = 500;
    private static final float START_ALPHA = 0.7f;
    private static final float END_ALPHA = 1f;

    private String online;
    private String responseData;
    private String ID;
    private String name;
    private String ONOFF;

    private Date create_time;
    private String create_t;
    private String unit_symbol;
    private Date update_at;
    private String update_t;
    private String uuid;
    private int current_value;
    @Override
    protected int getLayoutId() {
        return R.layout.acticity_device_led;
    }
    private mHandler mHandler = new mHandler();
    boolean SEND = true;
    // 其他页面
    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(toolbar).init();
        //隐藏状态栏
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        ImmersionBar.with(this).titleBar(R.id.detail_toolbar).keyboardEnable(true).init();
    }
    @Override
    protected void initView() {
        AppManager.getInstance().addActivity(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        mPopupWindow = new PopupWindow(this);
        animUtil = new AnimUtil();
        //init();
    }

    @Override
    protected void initData() {
        okHttpClient = new OkHttpClient();
        Intent i =getIntent();
        ID= i.getStringExtra("id");
        online= i.getStringExtra("online");
        Sai_id.setText(ID);
        Online.setText(online);
        if (online == "√"){
            //String o = String.valueOf(devices.get(i).getOnline());
            Online.setTextColor(Color.GREEN);
        }else {
            Online.setTextColor(Color.RED);
        }
        State.OTHER = false;

        toolbar.setTitle(i.getStringExtra("name"));
        GetInformation();

        Updatetime.setText(update_t);
        Create_time.setText(create_t);

    }


    @Override
    protected SwipeBackLayout getSwipeBackLayout(int layoutId) {
        return null;
    }




    @Override
    protected void setListener() {
        //toolbar返回按钮监听
        toolbar.setNavigationOnClickListener(v ->finish() );
    }
    @SuppressWarnings("AlibabaSwitchStatement")
    @OnClick({R.id.switch_led,R.id.btn_reset,R.id.iv_add})
    public void onClick(View v) {
        //noinspection AlibabaSwitchStatement
        switch (v.getId()){
            case R.id.switch_led:
                if (current_value == 1){
                    ONOFF = "0";
                }else {
                    ONOFF = "1";
                }
                SEND = true;
                PostInformation(ONOFF);
                break;
            case R.id.btn_reset:
                GetInformation();
                showMessage("刷新成功");
                break;
            case R.id.iv_add:

                showPop();
                toggleBright();

                break;
            default:
                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }
    @SuppressWarnings("AliDeprecation")
    private class mHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:

                    Updatetime.setText(update_t);
                    Create_time.setText(create_t);
                    if (current_value == 0){
                        Zhuangtai.setText("设备已打开");
                        img.setImageResource(R.mipmap.sss);
                    } else {
                        Zhuangtai.setText("设备已关闭");
                        img.setImageResource(R.mipmap.sss1);
                    }

                    break;

                default:break;
            }
        }
    }
    /**
     * TODO RX思维
     */
    public void GetInformation(){
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/" + ID + "/datastreams/" )
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);
        Observable.just(request)
                .subscribe(new Observer<Request>() {
                    //订阅成功
                    @Override
                    public void onSubscribe(@NotNull Disposable d) {
                        call.enqueue(new Callback() {
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                try {

                                    responseData = response.body().string();
                                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
                                    List<Data> streams = (List<Data>) app.getData();
                                    update_at = streams.get(0).getUpdate_at();
                                    create_time = streams.get(0).getCreate_time();
                                    current_value = Integer.parseInt(streams.get(0).getCurrent_value());
                                    unit_symbol = streams.get(0).getUnit_symbol();
                                    System.out.println(streams.get(0).getId());
                                    name = streams.get(0).getId();
                                    update_t = Utils.dateToString(update_at,"yyyy-MM-dd HH:mm:ss");
                                    create_t = Utils.dateToString(create_time,"yyyy-MM-dd HH:mm:ss");
                                    System.out.println(current_value);
                                    System.out.println(update_t);
                                    System.out.println(create_t);

                                    Message message = Message.obtain();
                                    message.what = 1;
                                    mHandler.sendMessage(message);

                                } catch (IOException e){
                                    e.printStackTrace();
                                }
                            }
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {

                            }

                        });
                    }
                    //上层给我的相应

                    @Override
                    public void onNext(@NotNull Request request) {
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                    //连接思维发生异常

                    @Override
                    public void onError(@NotNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    public void PostInformation( String onoff){

        new Thread()
        {
            @Override
            public void run() {
                URL url;
                HttpURLConnection connection;
                try {
                    System.out.println(onoff);
                    //data1代表云端的数据流是data1
                    String s1 = new String(",;" + name + "," + onoff);
                    byte[] data = s1.getBytes();
                    // 先new出一个URL对象，传入网络地址
                    // 调用openConnection()方法获取到HttpURLConnection对象
                    // 自己创建的中移物联网的地址http://api.heclouds.com/devices/25857699/datapoints?type=5
                    url = new URL("http://api.heclouds.com/devices/" + ID
                            + "/datapoints?type=5");
                    connection = (HttpURLConnection) url.openConnection();
                    // 下面使一些自由的定制，比如设置连接超时，读取超时的毫秒数，以及服务器希望得到的一些消息头
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("api-key", com.example.yt_app.Urils.State.ApiKey);
                    connection.setRequestProperty("Content-Length",
                            String.valueOf(data.length));
                    connection.setChunkedStreamingMode(5);
                    // 设置打开输出流
                    connection.setDoOutput(true);
                    // 拿到输出流
                    OutputStream os = connection.getOutputStream();
                    // 使用输出流往服务器提交数据
                    os.write(data);
                    os.flush();
                    os.close();
                    // //如果请求发送成功
                    if (connection.getResponseCode() == 200) {

                        // 接下来利用输入流对数据进行读取
                        InputStream is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(is));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            response.append(line);

                        }// 正常则返回{"errno":0,"error":"succ"}，此函数为void，用不上这个

                    }
                    // 最后关闭HTTP连接
                    connection.disconnect();
                    SEND = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Delay.Delay_ms(300);
                /*获取跟新数据*/
                GetInformation();
            }

        }.start();


    }

    private void showPop() {

        // 设置布局文件
        mPopupWindow.setContentView(LayoutInflater.from(this).inflate(R.layout.pop_add, null));
        // 为了避免部分机型不显示，我们需要重新设置一下宽高
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置pop透明效果
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
        // 设置pop出入动画
        //mPopupWindow.setAnimationStyle(R.style.pop_add);
        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
        mPopupWindow.setFocusable(true);
        // 设置pop可点击，为false点击事件无效，默认为true
        mPopupWindow.setTouchable(true);
        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
        mPopupWindow.setOutsideTouchable(true);
        // 相对于 + 号正下面，同时可以设置偏移量
        mPopupWindow.showAsDropDown(iv_add, -100, 0);
        // 设置pop关闭监听，用于改变背景透明度
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                toggleBright();

            }

        });

        tv_1 = mPopupWindow.getContentView().findViewById(R.id.tv_1);
        tv_2 = mPopupWindow.getContentView().findViewById(R.id.tv_2);
        tv_3 = mPopupWindow.getContentView().findViewById(R.id.tv_3);
        tv_4 = mPopupWindow.getContentView().findViewById(R.id.tv_4);
        tv_5 = mPopupWindow.getContentView().findViewById(R.id.tv_5);
        //设置按钮监听
        tv_1.setOnClickListener(v -> {
            showMessage("已在当前页面");
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        });
        tv_2.setOnClickListener(v -> {
            mPopupWindow.dismiss();
            Intent i= new Intent(getApplicationContext(),HistoryData.class);
            i.putExtra("id",ID);
            startActivity(i);
        });
        tv_4.setOnClickListener(v -> {
            mPopupWindow.dismiss();
            showMessage(tv_4.getText().toString());
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        });
        tv_3.setOnClickListener(v -> {
            mPopupWindow.dismiss();
            showMessage(tv_3.getText().toString());
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        });
        tv_5.setOnClickListener(v -> {
            mPopupWindow.dismiss();
            showMessage(tv_5.getText().toString());
            ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        });

    }

    private void toggleBright() {
        // 三个参数分别为：起始值 结束值 时长，那么整个动画回调过来的值就是从0.5f--1f的
        animUtil.setValueAnimator(START_ALPHA, END_ALPHA, DURATION);
        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
            @Override
            public void progress(float progress) {
                // 此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
                bgAlpha = bright ? progress : (START_ALPHA + END_ALPHA - progress);
                backgroundAlpha(bgAlpha);
            }
        });
        animUtil.addEndListner(new AnimUtil.EndListener() {
            @Override
            public void endUpdate(Animator animator) {
                // 在一次动画结束的时候，翻转状态
                bright = !bright;
            }
        });
        animUtil.startAnimator();
    }

    /**
     * 此方法用于改变背景的透明度，从而达到“变暗”的效果
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        // 0.0-1.0
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
        // everything behind this window will be dimmed.
        // 此方法用来设置浮动层，防止部分手机变暗无效
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        State.OTHER = true;
    }
}
